import { useEffect, useState } from "react";
import * as qs from "qs"
import {SearchPanel} from "./search-panel";
import {List} from "./list";

import {cleanObject, useMount, useDebounce} from "utils"
import { useHttp } from "utils/http";
import styled from "@emotion/styled";
import { Typography } from "antd";

const apiUrl = process.env.REACT_APP_API_URL;   

export const ProjectListScreen = () => {
    const [list, setList] = useState([])
    const [param, setParam] = useState({
        name: "",
        personId: "",
    })
    const debouncedParam = useDebounce(param, 2000)
    const [users, setUsers] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<null | Error>(null);
    const client = useHttp();
    useEffect(() => {
        setIsLoading(true);
        client("projects", {data: cleanObject(debouncedParam)})
        .then(setList)
        .catch(error => {
            setError(error);
            setList([]);
        })
        .finally(() => setIsLoading(false));
        // fetch(`${apiUrl}/projects?${qs.stringify(cleanObject(debouncedParam))}`).then(async response => {
        //     if(response.ok)
        //     {
        //         setList(await response.json())
        //     }
        // })
    }, [debouncedParam])

    useMount(() => {
        client("users").then(setUsers);
        // fetch(`${apiUrl}/users`).then(async response => {
        //     if(response.ok)
        //     {  
        //         setUsers(await response.json())
        //     }
        // })
    })
    
    return <Container>
        <h1>项目列表</h1>
        <SearchPanel param={param} setParam={setParam} users={users}/>
        {error ? <Typography.Text type={"danger"}>{error.message}</Typography.Text> : null}
        <List loading={isLoading} dataSource={list} users={users}/>
    </Container>
}

const Container = styled.div`
    padding: 3.2rem;
`